/**
* Description: 设备管理
*
* Created by hrx on 2023/9/16
*/
<template>
  <div class="device">
    <div class="content">
      <!-- 头部搜索栏 -->
      <div class="state" style="width: 100%">
        <div class="title">设备管理</div>
        <div class="left">
          <el-button :icon="Plus" type="primary" class="add-button" @click="addDevice"
          >
            创建设备
          </el-button>
          <el-button class="clear-button" @click="batchAdd">批量创建</el-button>
        </div>
        <el-form :model="form" inline label-position="top" class="rightForm">
          <el-form-item>
            <el-cascader
              v-model="form.data.regionList"
              :options="regionList"
              :props="{
                checkStrictly: true,
                multiple: true,
                value: 'id',
                label: 'regionName',
              }"
              :show-all-levels="false"
              filterable
              collapse-tags
              clearable
              class="cascader"
              placeholder="请选择所在区域"
              @change="cascaderChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="form.data.productIdList"
              placeholder="请选择设备型号"
              class="right20"
              style="width: 200px; height: 36px;"
              clearable
              multiple
              collapse-tags
              filterable
            >
              <el-option
                v-for="item in deviceModeList"
                :key="item.productId"
                :label="item.productName"
                :value="item.productId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              style="width: 160px; height: 36px;"
              placeholder="请输入设备编号"
              v-model="form.data.deviceCode"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="search-button"  @click="getListData('search')">搜索</el-button>
            <el-button class="clear-button" @click="resetData()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 数据展示部分 -->
      <div class="tablePage">
        <Table
          ref="tableRef"
          :not-data-img="$CONSTANTS.NOT_DATA_IMG"
          :table-columns="tableTitle"
          :remote-api="getDeviceListApi"
          :autoLoad="false"
          :pageNumberList="[10, 20, 50, 100]"
          ppageFieldName="page"
          pnumberFieldName="limit"
        >
          <template #index="scope">
            {{ scope.index + 1 }}
          </template>
          <template #deviceStatus="scope">
            <span :style="{color: $CONSTANTS.DEVICE_STATUS[scope.row.deviceStatus].COLOR}">
            {{ $CONSTANTS.DEVICE_STATUS[scope.row.deviceStatus].TITLE }}
            </span>
          </template>
          <template #operate="scope">
            <el-button class="edit-button" @click="editDevice(scope.row)">
              编辑
            </el-button>
            <el-button
              type="danger"
              :icon="Delete"
              class="delete-button"
              @click="delDevice(scope.row)"
            ></el-button>
          </template>
        </Table>
      </div>
    </div>
    <EditDevice ref="editDeviceRef" :mode="editMode" :device-mode-list="deviceModeList" :region-list="regionList" @afterSubmit="init" />
    <!--    批量上传设备（批量上传文件）-->
    <upload-file-dialog
      ref="uploadFileDialogRef"
      :demoUrl="demoUrl"
      title="批量创建设备"
      @afterSubmit="init"
      :upload-api="uploadDeviceApi"
    />
  </div>
</template>

<script setup lang="ts">
import {
  type queryDeviceListParam,
  type deviceDetailDTO,
  type regionTreeDTO,
  type deviceModelDTO,
  getDeviceListApi,
  getRegionTreeApi,
  getDeviceModelApi,
  delDeviceApi,
  uploadDeviceApi,
} from "@/api/device"
import {nextTick, onMounted, reactive, ref} from "vue";
import {IBaseQueryDataListParams} from "@/api";
import $CONSTANTS from "@/constants/globalConstants"
import {type ITableColumnItem} from "@/components/common/Table.vue"
import {Delete, Plus} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {diGuiHx} from "@/utils/common";

const tableRef = ref()
const editDeviceRef = ref()
const bindingUserDialogRef = ref()
const uploadFileDialogRef = ref()
const demoUrl = 'https://ambient-oss.oss-cn-hangzhou.aliyuncs.com/ambientMonitor/static/%E6%89%B9%E9%87%8F%E5%88%9B%E5%BB%BA%E8%AE%BE%E5%A4%87%E6%A8%A1%E6%9D%BF.xlsx';
const deviceModeList = ref<Array<deviceModelDTO>>([])
const regionList = ref<Array<regionTreeDTO>>([])
const editMode = ref<string>('add')

const form = reactive<IBaseQueryDataListParams<queryDeviceListParam>>({
  data: {
    deviceCode: undefined,
    regionList: undefined,
    productIdList: undefined,
    regionIdList: undefined,
  }
})
const tableTitle: Array<ITableColumnItem> = [
  {label: "序号", prop: "index", width: 80, template: true},
  {label: "设备编号", prop: "deviceCode"},
  {label: "设备型号", prop: "productName"},
  {label: "设备名称", prop: "deviceName"},
  {label: "联网状态", prop: "deviceStatus", template: true},
  {label: "所在层级", prop: "regionLevelGroupName"},
  {label: "所在区域", prop: "regionName"},
  {label: "安装点位", prop: "positionName"},
  {label: "最后同步时间", prop: "lastCommunicationTime", width: 180},
  {label: "创建时间", prop: "createTime", width: 180},
  {label: "操作", prop: "operate", template: true, fixed: "right", width: 150},
]

const init = () => {
  getListData('getData')
  getDeviceModeList();
  getRegionTree()
}
const getListData = (type: string) => {
  if (type == 'search') {
    tableRef?.value?.refreshData(form);
  } else {
    tableRef?.value?.queryData(form);
  }
}

const getDeviceModeList = async () => {
  let res = await getDeviceModelApi();
  deviceModeList.value = res.data.data
}
const getRegionTree = async () => {
  let res = await getRegionTreeApi();
  regionList.value = res.data.data
}

const addDevice = () => {
  editMode.value = 'add';
  editDeviceRef.value.dialogFormVisible = true;
}
const batchAdd = () => {
  uploadFileDialogRef.value.dialogFormVisible = true;
}
const resetData = () => {
  form.data = {
    deviceCode: undefined,
    regionList: undefined,
    productIdList: undefined,
    regionIdList: undefined,
  };
  tableRef.value.refreshData(form);
}

const delDevice = (row: deviceDetailDTO) => {
  ElMessageBox.confirm('确认要删除所选设备吗?', '提示', {type: 'warning',})
    .then(async () => {
      let res = await delDeviceApi(row.id);
      if (res.data.code == 0) {
        ElMessage.success('删除成功');
        getListData("getData");
      }
    })
}

const editDevice = (row: deviceDetailDTO) => {
  editMode.value = 'edit';
  editDeviceRef.value.dialogFormVisible = true;
  let regionArrayList = diGuiHx(row.regionId, regionList.value);
  row.regionList = regionArrayList;
  Object.assign(editDeviceRef.value.form, row)
  // .deviceCode = row.deviceCode;
}

const cascaderChange = (val: any) => {
  if(val){
    let regionIdListFun: any = []
    val.forEach((item: any) => {
      regionIdListFun.push(item[item.length - 1])
    })
    form.data.regionIdList = regionIdListFun;
  } else {
    form.data.regionIdList = []
  }
}


onMounted(() => {
  init()
})

</script>

<style lang="scss" scoped>
.device {
  height: 100%;
  .contentItems {
    h3 {
      font-size: 14px;
      font-weight: 700;
      margin-bottom: 10px;
    }
    p {
      font-size: 14px;
    }
  }
}
</style>